% 作者：功夫螃蟹
% 链接：https://www.zhihu.com/question/43309577/answer/3537040812
% 来源：知乎

clear; clc;

T = 0:.01:2*pi;
X = 12 * sin(T) - 4 * sin(3 * T);
Y = 13 * cos(T) - 5 * cos(2 * T) - 2 * cos(3 * T) - cos(4 * T);

a_x = [12, 0, -4, 0];
a_y = [13, -5, -2, -1];
a_p = (a_y + a_x) / 2;
a_n = (a_y - a_x) / 2;

writerObj = VideoWriter('heart.mp4', 'MPEG-4');
writerObj.FrameRate = 15;
open(writerObj);

figure;
for frame = 1:length(T)
    plot(X(1:frame), Y(1:frame),'b', 'LineWidth', 2);hold on;
    x = 0;
    y = 0;
    for i = 1:4
        xlim([-20, 20]);
        ylim([-20, 15]);
        plot([x, x + a_p(i) * sin(i * T(frame))], [y, y + a_p(i) * cos(i * T(frame))]);hold on;
        x = x + a_p(i) * sin(i * T(frame));
        y = y + a_p(i) * cos(i * T(frame));
        plot([x, x - a_n(i) * sin(i * T(frame))], [y, y + a_n(i) * cos(i * T(frame))]);hold on;
        x = x - a_n(i) * sin(i * T(frame));
        y = y + a_n(i) * cos(i * T(frame));
    end
    hold off;
    img = getframe(gcf);
    writeVideo(writerObj, img);
end

close(writerObj);

